<template>
  <div class="app-container app-container-full default-bg-color">
    <product-grid ref="productGrid" :exColumns="exColumns">
      <template #tbar>
        <el-button type="success" @click="onAdd()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button type="danger" @click="handleDelete()">
          <i-ep-delete />
          删除
        </el-button>
      </template>
      <template #column_oper_render="{ row }">
        <el-button type="primary" link size="small" @click="onEdit(row.id)">
          <i-ep-edit />
          编辑
        </el-button>
        <el-button type="primary" link size="small" @click="handleDelete(row.id)">
          <i-ep-delete />
          删除
        </el-button>
      </template>
    </product-grid>
    <!-- 弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body  @close="closeDialog">
      <product-form :id="productId" ref="productForm" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">保 存</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
  import ProductGrid from './product-grid.vue';
  import ProductForm from './product-form.vue';
  import { deleteProducts } from '@/api/system/product/index';

  const dialog = reactive({
    title: '项目信息',
    visible: false,
  });
  const productId = ref('');

  const exColumns = [{ field: 'oper', title: '操作', slots: { default: 'column_oper_render' } }];

  const productGrid = ref(ProductGrid);
  const productForm = ref(ProductForm);

  function onAdd() {
    productId.value = '';
    dialog.visible = true;
  }

  function onEdit(id) {
    productId.value = id;
    dialog.visible = true;
  }

  function handleDelete(id) {
    let ids = [];
    if (!id) {
      let selects = productGrid.value.productGrid.getCheckboxRecords();
      if (!selects) {
        ElMessage.warning('请选择要删除的数据');
        return;
      }
      for (const item of selects) {
        ids.push(item.id);
      }
    } else {
      ids.push(id);
    }

    deleteProducts(ids, true).then(() => {
      ElMessage.success('删除成功');
      productGrid.value.reload();
    });
  }

  function handleSubmit() {
    productForm.value.save();
  }

  function closeDialog() {
    productGrid.value.reload();
    productId.value = '';
  }
</script>
<style lang=""></style>
